﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevComponents.AdvTree;
using DevComponents.DotNetBar;
using PlanningGIS.Util.Data;
using PlanningGIS.ManageUtility;
using PlanningGIS.ManageUtility.DataAccess;
using PlanningGIS.ManageUtility.Modules;
using PlanningGIS.Win.Controls;
using PlanningGIS.Util.Drawing;
using System.Drawing.Imaging;
using System.IO;
using PlanningGIS.Util.IO;
using PlanningGIS.Framework;
using PlanningGIS.Util.Security;
using PlanningGIS.Util;
using PlanningGIS.Util.Regular;

namespace PlanningGIS.Manager
{
    /// <summary>
    /// 用户管理界面
    /// </summary>
    public partial class FrmUser :  DevComponents.DotNetBar.Metro.MetroForm
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        public FrmUser()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 加载窗体
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FrmUser_Load(object sender, EventArgs e)
        {
           // customValidator1.ValidateValue += customValidator1_ValidateValue;
           // txtPageIndex.Text = "1";
            BindData();
            if (_AllUsers == null || _AllUsers.Count == 0) btnAdd_Click(null, null);

            superTabItem1.Visible = false;
            dgrdvwAttach.Visible = false;
            btnUpload.Visible = false;
            btnDownload.Visible = false;
            sptbpnlMetial.Visible = false;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        //void customValidator1_ValidateValue(object sender, DevComponents.DotNetBar.Validator.ValidateValueEventArgs e)
        //{
        //    if (ManageHelper.SecuritySet.AllowFZD)
        //    {
        //        e.IsValid = VerifyHelper.ValidPassword(txtpsd.Text, 10, 3, 30);
        //    }
        //    else
        //    {
        //        e.IsValid = true;
        //    }
        //}

        /// <summary>
        /// 所有的用户，
        /// </summary>
        private List<UserInfo> _AllUsers = null;
        
        /// <summary>
        /// 绑定用户名称
        /// </summary>
        private void BindData()
        {
            _AllUsers = new List<UserInfo>();
            try
            {
                chkAduit.Visible = ManageHelper.CurrentUser.IsAdministrator();
                chkSecAdmin.Visible = ManageHelper.CurrentUser.IsAdministrator();
                chkSysAdmin.Visible = !ManageHelper.SecuritySet.SplitUser || ManageHelper.CurrentUser.IsAdministrator();
                //chkAduit.Visible = ManageHelper.SecuritySet.SplitUser;
                //chkSecAdmin.Visible = ManageHelper.SecuritySet.SplitUser;
                itmpnlRoles.Enabled = (ManageHelper.CurrentUser.IsAdministrator() || ManageHelper.CurrentUser.IsSecurityAdmin());
                ChangedControl(zjgisOperateType.UnKnow);
                EnableControl(zjgisOperateType.UnKnow);
                cmbDepartment.BindData();
                cmbDepartmentUser.BindData();
                DataTable dtRole = RoleAccess.GetRoleTag();
                if (dtRole != null && dtRole.Rows.Count > 0)
                {
                    foreach (DataRow r in dtRole.Rows)
                    {
                        CheckBoxItem chk = new CheckBoxItem();
                        chk.Name = r["ID"].ToString();
                        chk.Text = r["Name"].ToString();
                        chk.Checked = false;
                        itmpnlRoles.Items.Add(chk);
                    }
                }
                DataTable dt = UserAccess.GetUserTag(!ManageHelper.CurrentUser.IsAdministrator() && ManageHelper.SecuritySet.SplitUser);
                if (dt == null || dt.Rows.Count == 0)
                {
                    ChangedControl(zjgisOperateType.Add);
                    EnableControl(zjgisOperateType.Add);
                    return;
                }
                _AllUsers = dt.ToObject<UserInfo>();
                lblTotal.Text = dt.Rows.Count.ToString();
                foreach (DataRow dr in dt.Rows)
                {
                    string dpid = dr["department_id"].ToString();
                    if (string.IsNullOrWhiteSpace(dpid)) dpid = cmbDepartmentUser.DefaultID;
                    Node[] nd = cmbDepartmentUser.Nodes.Find(dpid, true);
                    if (nd != null && nd.Length > 0)
                    {
                        Node tmpnd = new Node();
                        tmpnd.Text = dr["name"].ToString();
                        tmpnd.Name = dr["id"].ToString();
                        tmpnd.Tag = dr["id"].ToString();
                        nd[0].Nodes.Add(tmpnd);
                    }
                }
                txtPageIndex.Text = "1";
                SetPageIndex();
            }
            catch (Exception ex)
            {
                MsgHelper.ShowErrorMsgbox(ex.ToString());
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        /// <param name="op">0只读；1新增；2修改；3删除；</param>
        private void RefreshData(string id, zjgisOperateType op)
        {
            try
            {
                if (_AllUsers == null) _AllUsers = new List<UserInfo>();
                ChangedControl(zjgisOperateType.UnKnow);
                EnableControl(zjgisOperateType.UnKnow);
                if (op ==  zjgisOperateType.Delete)
                {
                    Node[] nd = cmbDepartmentUser.Nodes.Find(id, true);
                    if (nd != null && nd.Length > 0)
                        nd[0].Remove();
                    UserInfo u = _AllUsers.FirstOrDefault(t => t.ID == id);
                    if (u != null)
                    {
                        _AllUsers.Remove(u);
                    }
                }
                else if (op ==  zjgisOperateType.Update || op ==  zjgisOperateType.Add)
                {
                    UserInfo u = ManageHelper.DBContext.GetEntryByID<UserInfo>(id);
                    if (u == null) return;
                    if (op == zjgisOperateType.Update)
                    {
                        Node[] nd = cmbDepartmentUser.Nodes.Find(id, true);
                        if (nd != null && nd.Length > 0)
                        {
                            nd[0].Text = u.Name;
                            nd[0].Tag = u.ID;
                        }
                    }
                    else
                    {
                        int num = 0;
                        if (!lblTotal.Text.Contains("{"))
                            num = (int.Parse(lblTotal.Text) + 1);
                        lblTotal.Text = num.ToString();
                        string dpid = u.DepartMent_ID;
                        if (string.IsNullOrWhiteSpace(dpid)) dpid = cmbDepartmentUser.DefaultID;
                        Node[] nd = cmbDepartmentUser.Nodes.Find(dpid, true);
                        if (nd != null && nd.Length > 0)
                        {
                            Node tmpnd = new Node();
                            tmpnd.Text = u.Name;
                            tmpnd.Name = u.ID;
                            tmpnd.Tag = u.ID;
                            nd[0].Nodes.Add(tmpnd);
                        }
                        _AllUsers.Add(u);
                    }
                }
                lblTotal.Text = _AllUsers.Count.ToString();
                SetPageIndex();
            }
            catch (Exception ex)
            {
                MsgHelper.ShowErrorMsgbox(ex.Message);
            }
        }
        
        /// <summary>
        /// 部门用户选择改变
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cmbDepartmentUser_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbDepartmentUser.SelectedNode == null || cmbDepartmentUser.SelectedNode.Tag == null) return;
            if (!(cmbDepartmentUser.SelectedNode.Tag is string)) return;
            int idx = _AllUsers.FindIndex(t => t.ID.Equals(cmbDepartmentUser.SelectedNode.Tag.ToString()));
            txtPageIndex.Text = (idx + 1).ToString();
            SetPageIndex();
        }

        /// <summary>
        /// 绑定用户信息
        /// </summary>
        /// <param name="id"></param>
        private void BindInfo(string id)
        {
            try
            {
                ChangedControl(zjgisOperateType.UnKnow);
                EnableControl(zjgisOperateType.UnKnow);    
                UserInfo u = ManageHelper.DBContext.GetEntryByID<UserInfo>(id);
                if (u == null) return;
                txtLogin.Text = u.Login_Name;
                txtName.Text = u.Name;
                txtpsd.Text = "";
                txtpsd.Tag = u.PSD;
                cmbDepartment.SetSelectValue(u.DepartMent_ID);
                txtOfficePhone.Text = u.OfficePhone;
                txtMobile.Text = u.MobilePhone;
                txtLogin.Tag = u.ID;
                //if (u.SecretStatus == "1") rdoSecret1.Checked = true;
                //else if (u.SecretStatus == "2") rdoSecret2.Checked = true;
                //else rdoSecret0.Checked = true;
                txtName.Tag = u.Login_Name;
                swtbtnActive.Value = u.IsActive == "1" ? true : false;
                chkSysAdmin.Checked = u.IsSystemAdmin();
                chkSecAdmin.Checked = u.IsSecurityAdmin();
                chkAduit.Checked = u.IsAuditAdmin();
                DataTable dtUserRole = ManageHelper.DBContext.GetDataTableByID("USER_ROLE_REL", id, "user_id");
                foreach (BaseItem itm in itmpnlRoles.Items)
                {
                    if (!(itm is CheckBoxItem)) continue;
                    CheckBoxItem chk = (CheckBoxItem)itm;
                    chk.Checked = false;
                    if (dtUserRole != null && dtUserRole.Rows.Count > 0)
                    {
                        DataRow[] rs = dtUserRole.Select("role_id='" + chk.Name + "'");
                        if (rs != null && rs.Length > 0) chk.Checked = true;
                    }
                }
                dgrdvwAttach.Rows.Clear();
                DataTable dtAttach = UserAccess.GetUserAttach(id);
                if (dtAttach != null && dtAttach.Rows.Count > 0)
                {
                    foreach (DataRow r in dtAttach.Rows)
                    {
                        dgrdvwAttach.Rows.Add(new string[] { r["attid"].ToString(), r["arid"].ToString(), r["filename"].ToString(), "" });
                    }
                }
            }
            catch (Exception ex)
            {
                MsgHelper.ShowErrorMsgbox(ex.ToString());
            }         
        }

        /// <summary>
        /// 改变控件的状态
        /// </summary>
        /// <param name="op">0只读；1新增；2修改；</param>
        private void ChangedControl(zjgisOperateType op)
        {
            txtLogin.ReadOnly = op == zjgisOperateType.UnKnow ? true : false;
            txtName.ReadOnly = op == zjgisOperateType.UnKnow ? true : false;
            txtpsd.ReadOnly = op == zjgisOperateType.UnKnow ? true : false;
            cmbDepartment.Enabled = op == zjgisOperateType.UnKnow ? false : true;
            txtOfficePhone.ReadOnly = op == zjgisOperateType.UnKnow ? true : false;
            txtMobile.ReadOnly = op == zjgisOperateType.UnKnow ? true : false;
            swtbtnActive.Enabled = op == zjgisOperateType.UnKnow ? false : true;
            chkAduit.Enabled = op == zjgisOperateType.UnKnow ? false : true;
            chkSecAdmin.Enabled = op == zjgisOperateType.UnKnow ? false : true;
            chkSysAdmin.Enabled = op == zjgisOperateType.UnKnow ? false : true;
            itmpnlRoles.Enabled = op == zjgisOperateType.UnKnow ? false : true;
            btnUpload.Enabled = op == zjgisOperateType.UnKnow ? false : true;
            if (op == zjgisOperateType.Add)
            {
                txtLogin.Text = "";
                txtLogin.Tag = null;
                txtName.Text = "";
                txtName.Tag = null;
                txtpsd.Text = "";
                txtpsd.Tag = null;
                txtValidPsd.Text = "";
                txtOfficePhone.Text = ""; 
                txtMobile.Text = "";
                dgrdvwAttach.Rows.Clear();
                chkSysAdmin.Checked = false;
                chkSecAdmin.Checked = false;
                chkAduit.Checked = false;
                swtbtnActive.Value = false;
                if (itmpnlRoles.Items.Count > 0)
                {
                    foreach (BaseItem itm in itmpnlRoles.Items)
                    {
                        if (!(itm is CheckBoxItem)) continue;
                        CheckBoxItem chk = (CheckBoxItem)itm;
                        chk.Checked = false;
                    }
                }                
            }
        }

        /// <summary>
        /// 改变按钮状态
        /// </summary>
        /// <param name="op"></param>
        private void EnableControl(zjgisOperateType op)
        {
            btnAdd.Enabled = op == zjgisOperateType.UnKnow ? true : false;
            btnEdit.Enabled = op == zjgisOperateType.UnKnow ? true : false;
            btnSave.Enabled = op != zjgisOperateType.UnKnow ? true : false; 
        }

        /// <summary>
        /// 添加用户
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAdd_Click(object sender, EventArgs e)
        {
            if (ManageHelper.CurrentUser.IsAdministrator() || ManageHelper.CurrentUser.IsSystemAdmin())
            {
                EnableControl(zjgisOperateType.Add);
                ChangedControl(zjgisOperateType.Add);
                swtbtnActive.Enabled = false;
                itmpnlRoles.Enabled = false;
                if (ManageHelper.CurrentUser.IsAdministrator() || ManageHelper.CurrentUser.IsSecurityAdmin() ||
                    !ManageHelper.SecuritySet.SplitUser)
                {
                    swtbtnActive.Enabled = true;
                    itmpnlRoles.Enabled = true;
                }
            }
            else
            {
                MsgHelper.ShowInfomationMsgbox("您不是系统管理员，不能新增用户！");
                return;
            }            
        }

        /// <summary>
        /// 退出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnEdit_Click(object sender, EventArgs e)
        {
            if (ManageHelper.CurrentUser.IsAdministrator() || ManageHelper.CurrentUser.IsSecurityAdmin()
               || !ManageHelper.SecuritySet.SplitUser)
            {
                EnableControl(zjgisOperateType.Update);
                ChangedControl(zjgisOperateType.Update);
                swtbtnActive.Enabled = false;
                itmpnlRoles.Enabled = false;
                if (ManageHelper.CurrentUser.IsAdministrator() || ManageHelper.CurrentUser.IsSecurityAdmin()
                    || !ManageHelper.SecuritySet.SplitUser)
                {
                    swtbtnActive.Enabled = true;
                    itmpnlRoles.Enabled = true;
                }
            }
            else
            {
                MsgHelper.ShowInfomationMsgbox("您不是安全保密管理员，不能修改用户！");
                return;
            }
            
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (txtLogin.Tag == null || string.IsNullOrWhiteSpace(txtLogin.Tag.ToString())) return;
            if (txtName.Tag != null)
            {
                string loginname = (string)txtName.Tag;
                if (loginname.Equals(ManageHelper.CurrentUser.Login_Name, StringComparison.CurrentCultureIgnoreCase))
                {
                    MsgHelper.ShowErrorMsgbox("您不能删除当前登录的用户");
                    return;
                }
            }
            DialogResult dlg = MsgHelper.ShowYesOrNoQueryMsgBox("您是否确定要删除用户【" + txtName.Text + "】的信息？");
            if (dlg != DialogResult.Yes) return;
            try
            {
                string id =txtLogin.Tag.ToString();
                int rst = ManageHelper.DBContext.Delete(
                    new List<string> { "USERINFO", "USER_ROLE_REL" },
                    new List<string> { id, id }, 
                    new List<string> { "id", "user_id" });
                if (rst > 0)
                {
                    //Log.WriteLog(ManageHelper.CurrentUser.Name, Log.zjgisLogType.DeleteUser, Log.zjgisLogStatus.Success, txtName.Text);
                    ChangedControl(zjgisOperateType.UnKnow);
                    RefreshData(id, zjgisOperateType.Delete);
                    MsgHelper.ShowInfomationMsgbox("操作成功");
                }
                else MsgHelper.ShowErrorMsgbox("操作失败");
            }
            catch (Exception ex)
            {
                MsgHelper.ShowErrorMsgbox(ex.ToString());
            }
            
        }

        /// <summary>
        /// 撤销当前操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnReturn_Click(object sender, EventArgs e)
        {
            ChangedControl(zjgisOperateType.UnKnow);
            SetPageIndex();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void chkSysAdmin_CheckedChanged(object sender, EventArgs e)
        {
            if (!ManageHelper.SecuritySet.SplitUser)
            {
                chkAduit.Checked = chkSysAdmin.Checked;
                chkSecAdmin.Checked = chkSysAdmin.Checked;
            }
        }

        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSave_Click(object sender, EventArgs e)
        {
            if (!ValidUser()) return;
            zjgisOperateType op =  zjgisOperateType.Add;
            UserInfo u = new UserInfo()
            {
                Name = txtName.Text.Trim(),
                MobilePhone = txtMobile.Text.Trim(),
                OfficePhone = txtOfficePhone.Text.Trim(),
                Login_Name = txtLogin.Text.Trim(),
                DepartMent_ID = cmbDepartment.SelectedDepartmentID,
                Admin_Type = (chkSysAdmin.Checked ? "T" : "F") + (chkSecAdmin.Checked ? "T" : "F") + (chkAduit.Checked ? "T" : "F"),
                Status = "unlock",
                IsActive = swtbtnActive.Value ? "1" : "0"
            };
            //if (rdoSecret1.Checked) u.SecretStatus = "1";
            //else if (rdoSecret2.Checked) u.SecretStatus = "2";
            //else u.SecretStatus = "0";
            this.Cursor = Cursors.WaitCursor;
            int rst = 0;
            Log log = new Log();
            log.USER_NAME = ManageHelper.CurrentUser.Name;
            log.OP_TYPE = PlanningGIS.ManageUtility.Modules.zjgisLogType.Login;
            log.NOTES = ManageHelper.CurrentUser.Name + "试图登录运行维护管理系统！";
            log.OP_STATUS = zjgisLogStatus.Fail;
            try
            {
                if (txtLogin.Tag == null)
                {
                    if (UserAccess.IsSameLoginName(u.Login_Name))
                    {
                        MsgHelper.ShowErrorMsgbox("登录名重复，请重新输入！");
                        return;
                    }
                    if (string.IsNullOrWhiteSpace(txtpsd.Text))
                    {
                        MsgHelper.ShowErrorMsgbox("密码不正确，请重新输入！");
                        return;
                    }                
                    if (swtbtnActive.Value) u.EffectiveTime = ManageHelper.DBContext.GetSysDateTime();
                    u.ID = DateTime.Now.ToString("yyyyMMddHHmmssfff") + _AllUsers.Count.ToString().PadLeft(4, '0');
                    u.PSD = SecurityHelper.EnCryptUnidirectional(txtpsd.Text.Trim(), AppConfig.SystemConfig.基本信息.密钥);
                    rst = ManageHelper.DBContext.Insert<UserInfo>(u);
                }
                else
                {
                    op = zjgisOperateType.Update;
                    if (string.IsNullOrWhiteSpace(txtLogin.Tag.ToString())) return;
                    u.ID = txtLogin.Tag.ToString();
                    if (string.IsNullOrWhiteSpace(txtpsd.Text)) u.PSD = txtpsd.Tag==null?"": txtpsd.Tag.ToString();
                    else
                    {
                        u.PSD = SecurityHelper.EnCryptUnidirectional(txtpsd.Text, AppConfig.SystemConfig.基本信息.密钥);
                    }
                    if (UserAccess.IsSameLoginName(u.Login_Name, u.ID))
                    {
                        MsgHelper.ShowErrorMsgbox("登录名重复，请重新输入！");
                        return;
                    }
                    if (swtbtnActive.Value)
                    {
                        if (swtbtnActive.Tag == null || (DateTime)swtbtnActive.Tag == DateTime.MinValue || !string.IsNullOrWhiteSpace(txtpsd.Text))
                            u.EffectiveTime = ManageHelper.DBContext.GetSysDateTime();
                    }
                    rst = ManageHelper.DBContext.Update<UserInfo>(u, "id", txtLogin.Tag.ToString(), true);
                }
                if (rst > 0)
                {
                    SaveRole(u);
                    SaveAttach(u.ID);
                    ChangedControl(zjgisOperateType.UnKnow);
                    RefreshData(u.ID, op);
                    MsgHelper.ShowInfomationMsgbox("操作成功");
                }
                else
                {
                    MsgHelper.ShowErrorMsgbox("操作失败");
                }
                EnableControl(zjgisOperateType.UnKnow);
            }
            catch (Exception ex)
            {
                MsgHelper.ShowErrorMsgbox(ex.ToString());
                EnableControl(zjgisOperateType.UnKnow);
            }
            finally
            {
                if (!AppConfig.IsRunLocal) Log.WriteLog(log);
                this.Cursor = Cursors.Default;
            }

        }

        /// <summary>
        /// 验证输入的值是否有效
        /// </summary>
        /// <returns></returns>
        private bool ValidUser()
        {
            if (string.IsNullOrWhiteSpace(txtName.Text))
            {
                MsgHelper.ShowErrorMsgbox("姓名不能为空");
                txtName.Focus();
                return false;
            }
            if (string.IsNullOrWhiteSpace(txtLogin.Text))
            {
                MsgHelper.ShowErrorMsgbox("登录名称不能为空");
                txtLogin.Focus();
                return false;
            }
            return true;
        }

        /// <summary>
        /// 保存角色信息
        /// </summary>
        /// <param name="u"></param>
        private void SaveRole(UserInfo u)
        {
            if (itmpnlRoles.Items.Count == 0) return;
            try
            {
                ManageHelper.DBContext.Delete("USER_ROLE_REL", u.ID, "user_id");
                List<Dictionary<string, dynamic>> ps = new List<Dictionary<string, dynamic>>();
                foreach (BaseItem itm in itmpnlRoles.Items)
                {
                    if (!((CheckBoxItem)itm).Checked) continue;
                    Dictionary<string, dynamic> p = new Dictionary<string, dynamic>();
                    p.Add(":id", Guid.NewGuid().ToString());
                    p.Add(":user_id", u.ID);
                    p.Add(":role_id", itm.Name);
                    ps.Add(p);
                }
                if (ps.Count > 0)
                {
                    string sql = "insert into USER_ROLE_REL(id,user_id,role_id) values(:id,:user_id,:role_id) ";
                    ManageHelper.DBContext.ExecuteNonQuery(sql, ps);
                }
            }
            catch (Exception ex )
            {
                MsgHelper.ShowErrorMsgbox(ex.Message);
            }
        }

        /// <summary>
        /// 保存附件
        /// </summary>
        /// <param name="uid"></param>
        private void SaveAttach(string uid)
        {
            if (dgrdvwAttach.Rows.Count == 0) return;
            string msg = "";
            foreach (DataGridViewRow r in dgrdvwAttach.Rows)
            {
                try
                {
                    string attid = Guid.NewGuid().ToString();
                    if (r.Cells[dgrdvwcolID.Index].Value == null || string.IsNullOrWhiteSpace(r.Cells[dgrdvwcolID.Index].Value.ToString()))
                    {
                        AttachMent a = new AttachMent()
                        {
                            ID = attid,
                            FileName = r.Cells[dgrdvwcolFileName.Index].Value.ToString(),
                            UploadDate = DateTime.Now,
                            Content = FileHelper.ReadByte(r.Cells[dgrdvwcolPath.Index].Value.ToString())
                        };
                        if (ManageHelper.DBContext.Insert<AttachMent>(a) > 0)
                        {
                            r.Cells[dgrdvwcolID.Index].Value = attid;
                        }
                    }
                    if (r.Cells[dgrdvwcolRelID.Index].Value == null || string.IsNullOrWhiteSpace(r.Cells[dgrdvwcolRelID.Index].Value.ToString()))
                    {
                        Attach_Rel rel = new Attach_Rel()
                        {
                            ID = Guid.NewGuid().ToString(),
                            AttachID = attid,
                            RelID = uid
                        };
                        if (ManageHelper.DBContext.Insert<Attach_Rel>(rel) > 0)
                        {
                            r.Cells[dgrdvwcolRelID.Index].Value = rel.ID;
                        }
                    }
                }
                catch (Exception ex)
                {
                    msg += ex.Message + ";";
                }                
            }
            if (!string.IsNullOrWhiteSpace(msg))
            {
                MsgHelper.ShowErrorMsgbox(msg);
            }
        }

        /// <summary>
        /// 输入页码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtPageIndex_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode != Keys.Enter) return;
            if (string.IsNullOrWhiteSpace(txtPageIndex.Text)) return;
            if (_AllUsers == null || _AllUsers.Count == 0) return;
            int idx = 0;
            if (!int.TryParse(txtPageIndex.Text, out idx)) return;
            if (idx < 1) idx = 1;
            if (idx > _AllUsers.Count) idx = _AllUsers.Count;
            txtPageIndex.Text = idx.ToString();
            SetPageIndex();
        }

        /// <summary>
        /// 第一个
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnFirst_Click(object sender, EventArgs e)
        {
            if (_AllUsers == null || _AllUsers.Count == 0) return;
            txtPageIndex.Text = "1";
            SetPageIndex();
        }

        /// <summary>
        /// 上一个
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnForward_Click(object sender, EventArgs e)
        {
            if (_AllUsers == null || _AllUsers.Count == 0) return;
            int idx = int.Parse(txtPageIndex.Text) - 1;
            if (idx < 1) idx = 1;
            txtPageIndex.Text = idx.ToString();
            SetPageIndex();
        }

        /// <summary>
        /// 下一个
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnNext_Click(object sender, EventArgs e)
        {
            if (_AllUsers == null || _AllUsers.Count == 0) return;
            int idx = int.Parse(txtPageIndex.Text) + 1;
            if (idx > _AllUsers.Count) idx = _AllUsers.Count;
            txtPageIndex.Text = idx.ToString();
            SetPageIndex();
        }

        /// <summary>
        /// 最后一个
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnLast_Click(object sender, EventArgs e)
        {
            if (_AllUsers == null || _AllUsers.Count == 0) return;
            txtPageIndex.Text = _AllUsers.Count.ToString();
            SetPageIndex();
        }

        /// <summary>
        /// 
        /// </summary>
        private void SetPageIndex()
        {
            
            int idx = int.Parse(txtPageIndex.Text);
            if (_AllUsers == null || _AllUsers.Count == 0)
            {
                ChangedControl(zjgisOperateType.UnKnow);
                EnableControl(zjgisOperateType.UnKnow);    
                return;
            }
            if (idx - 1 == _AllUsers.Count)
            {
                idx -= 1;
                txtPageIndex.Text = idx.ToString();
            }
            if (idx - 1 < 0) return;
            BindInfo(_AllUsers[idx - 1].ID);
        }

        /// <summary>
        /// 上传附件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnUpload_Click(object sender, EventArgs e)
        {
            openFileDialog.Filter = "PDF文档|*.pdf";
            if (openFileDialog.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
            {
                foreach (string f in openFileDialog.FileNames)
                {
                    dgrdvwAttach.Rows.Add(new string[] { "", "", Path.GetFileName(f), f });
                }
            }
        }

        /// <summary>
        /// 下载附件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDownload_Click(object sender, EventArgs e)
        {
            if (dgrdvwAttach.SelectedRows.Count == 0)
            {
                MsgHelper.ShowInfomationMsgbox("请先选择要下载的附件");
                return;
            }
            if (folderBrowserDialog.ShowDialog(this) != System.Windows.Forms.DialogResult.OK) return;
            string p = folderBrowserDialog.SelectedPath;
            foreach (DataGridViewRow r in dgrdvwAttach.SelectedRows)
            {
                if (r.Cells[dgrdvwcolID.Index].Value == null || string.IsNullOrWhiteSpace(r.Cells[dgrdvwcolID.Index].Value.ToString())) continue;
                string id = r.Cells[dgrdvwcolID.Index].Value.ToString();
                AttachMent a = ManageHelper.DBContext.GetEntryByID<AttachMent>(id);
                if (a == null || a.Content == null || a.Content.Length < 10) continue;
                FileHelper.WriteFile(p + "\\" + a.FileName, a.Content);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtpsd_TextChanged(object sender, EventArgs e)
        {
            int cnt = VerifyHelper.PasswordComplex(txtpsd.Text);
            foreach (StepItem itm in stpPsd.Items)
            {
                itm.Value = 0;
            }
            if (cnt < 2) ((StepItem)stpPsd.Items[0]).Value = 100;
            else ((StepItem)stpPsd.Items[cnt - 2]).Value = 100;
        }

        
    }
}